package com.huodongrili.calender;

import java.io.File;

import android.app.Application;
import android.content.Intent;

import com.baidu.mapapi.BMapManager;
import com.huodongrili.calender.bg.ScheduleService;
import com.huodongrili.calender.data.Constant;
import com.huodongrili.calender.data.DataPreferences;
import com.huodongrili.calender.util.ECLog;
import com.huodongrili.calender.util.FileUtil;

public class ECApplication extends Application {

	
	private BMapManager mBMapMan = null;
	
	@Override
	public void onCreate() {
		super.onCreate();

		if (BuildConfig.DEBUG) {
			ECLog.debug("ECApplication onCreate...");
		}
		
		mBMapMan = new BMapManager(getApplicationContext());
		mBMapMan.init(Constant.MAP_KEY_BAIDU, null);
		

		DataPreferences dataP = DataPreferences.getInstance(getApplicationContext());

		if (dataP.isFirstRun()) {

			loadFile();

			dataP.setFirstRun(false);

		}
		
		if(dataP.isWifiSync()){
			startService(new Intent(this,ScheduleService.class));
		}
	   
	}
	
	
	@Override
	public void onTerminate() {
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		super.onTerminate();
	}
	
	
	public BMapManager getBManager(){
		return mBMapMan;
	}

	private void loadFile() {

		File root = getCacheDir().getParentFile();
		File dbroot = new File(root.getAbsolutePath() + "/databases");
		if (!dbroot.exists()) {
			dbroot.mkdir();
		}

		File ecDb = getDatabasePath(Constant.LOCAL_DB_NAME);

		if (!ecDb.exists()) {
			FileUtil.GetAssetsFile(this, Constant.LOCAL_DB_NAME,
					ecDb.getAbsolutePath(), true);
		}

	}
}
